package com.terrace.controller.system;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.terrace.web.model.DataGrid;
import com.terrace.db.system.mapper.entity.Log;
import com.terrace.db.system.mapper.entity.LogWithDetails;
import com.terrace.db.system.service.LogService;
import com.terrace.core.mybatis.entity.Pagination;

/**
 * 系统日志查询
 * @author jiangyg
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/logs")
public class LogsController {
	
	@Autowired
	private LogService logService;
	
	/**
	 * 默认管理页面
	 * @param request
	 * @return
	 */
	@RequestMapping
	public ModelAndView logList(HttpServletRequest request){
		return new ModelAndView("system/log/logList");
	}
	
	/**
	 * 日志详情
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(params = "logDetails")
	public ModelAndView logDetails(@RequestParam(value = "id") int logId, HttpServletRequest request) throws UnsupportedEncodingException{
		LogWithDetails details = logService.selectLogDetailsById(logId);
		if(details != null) {
			String encoder = "GBK";
			byte[] requestDetails = details.getRequestDetails();
			byte[] responseDetails = details.getResponseDetails();
			request.setAttribute("requestDetails", new String(requestDetails, encoder));
			request.setAttribute("responseDetails", new String(responseDetails, encoder));
		}
		return new ModelAndView("system/log/logDetails");
	}
	
	/**
	 * 数据表格
	 * @param request
	 * @param pagination
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "datagrid")
	@RequiresPermissions("system:logs:view")
	public DataGrid<Log> datagrid(Log log, Pagination<Log> pagination, HttpServletRequest request) {
		DataGrid<Log> dataGrid = new DataGrid<Log>();
		dataGrid.setPagination(logService.selectLogsForPagination(pagination, log));
		return dataGrid;
	}
	
}
